#!/bin/bash

loginServer=("loginmgr" "corecenter")
imServer=("front" "session" "imcenter")

#functions
startLogin() {
	for (( index=${#loginServer[@]}-1; index>=0; --index)); do
		server=${loginServer[$index]}
		./$server $server.xml &
		if [ $? -eq 0 ]; then
			echo "$server start success!"
		else
			echo "$server start failed..."
		fi
		sleep 2
	done
}

stopLogin() {
	for server in ${loginServer[@]}; do
		pkill $server
		if [ $? -eq 0 ]; then
			echo "kill $server success! "
		else
			echo "kill $server failed..."
		fi
		sleep 2
	done
}

startIM() {
	for (( index=${#imServer[@]}-1; index>=0; --index)); do
		server=${imServer[$index]}

		#session server special handling
		if [ $server == "session" ]; then
			./$server sm.xml &		
			if [ $? -eq 0 ]; then
				echo "session1 start success! "
			else
				echo "session1 start failed..."
			fi
			sleep 1
			./$server sm.xml &		
			if [ $? -eq 0 ]; then
				echo "session2 start success! "
			else
				echo "session2 start failed..."
			fi
		else
			./$server $server.xml &
			if [ $? -eq 0 ]; then
				echo "$server start success!"
			else
				echo "$server start failed..."
			fi
		sleep 2
		fi
	done
}

stopIM() {
	for server in ${imServer[@]}; do
		pkill $server
		if [ $? -eq 0 ]; then
			echo "kill $server success! "
		else
			echo "kill $server failed..."
		fi
		sleep 2
	done
}

start() {
	startLogin
	sleep 1
	startIM
}

stop() {
	stopIM
	sleep 1
	stopLogin
}

restart() {
	stop;
	start;
}

#logic
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		restart
		;;
	startlogin)
		startLogin
		;;
	stoplogin)
		stopLogin
		;;
	startim)
		startIM
		;;
	stopim)
		stopIM
		;;
	help|*)
		echo $"Usage: $0 {start|stop|restart|startLogin|stopLogin|startIM|stopIM}"
		cat <<EOF

			start       - start all server
			stop        - stop all server
			restart     - restart all server
			startLogin  - start corecenter && loginmgr
			stopLogin   - stop loginmgr && corecenter
			startIM     - start imcenter && session1 && session2 && front
			stopIM      - stop front && all session && imcenter

EOF
		exit 1
		;;	
esac

exit 0
